﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using CsQuery;
using FictionsDownload.BLL;
using FictionsDownload.BLL.CefSharp;
using FictionsDownload.DAL;
using FictionsDownload.Enums;
using FictionsDownload.Events;
using Zzw;
using FictionsDownload.Model;
using FictionsDownload.Static;
using static FictionsDownload.UI.FormCefSharp;

namespace FictionsDownload.UI
{
    public partial class FormQidian : Form
    {
        #region 内部变量和属性
        private BLL.Book book = new BLL.Book();
        private BLL.Directory directory = new BLL.Directory();
        private BLL.Folder folder = new BLL.Folder();
        private BLL.WebFormat webFormat = new BLL.WebFormat();
        private FormCefSharp formCefSharp;
        private CefSharpQueue CefSharpQueue;
        #endregion
        #region 公共属性和事件
        public event EventHandler UserNameChanged;
        #endregion
        #region 构造初始化
        public FormQidian()
        {
            InitializeComponent();
            FormCefSharpInit();
            rtboxMsgInit();
            rtbox_Html_Init();
            lvBookcaseInit();
        }
        private void FormCefSharpInit()
        {
            //pl_TitleBar 的起点是最左边最上面
            this.pl_web.Location = new Point(0, 30);
            //web_Auto布局
            this.pl_web.Size = new Size(this.ClientSize.Width-this.rtboxMsg.Size.Width, this.Size.Height - this.rtbox_Html.Location.Y - this.pl_web.Location.Y);
            //实例对象 
            formCefSharp = FormCefSharp.GetIntance(CefSharpQidian.GetIntance);
            //容器设置
            formCefSharp.Parent = this.pl_web;
            formCefSharp.Dock = DockStyle.Fill;
            //窗口布局完成后，控件二次调整
            formCefSharp.InitializeComponentCode();
            //CefSharp事件
            formCefSharp.webBrowser.UserNameChanged += new EventHandler(CefSharpUserNameChange);
            formCefSharp.webBrowser.AddMessage += new AddMessageEventHandler(AddMessageEvent);
            formCefSharp.webBrowser.WebBrowser.FrameLoadEnd += new EventHandler<FrameLoadEndEventArgs>(HtmlLoadEnd);
            //队列控制事件
            CefSharpQueue = new CefSharpQueue(formCefSharp.webBrowser);
            CefSharpQueue.AddMessage += new AddMessageEventHandler(AddMessageEvent);
            CefSharpQueue.LvBookcaseRefresh += new EventHandler(lvBookcaseRefresh);
        }
        private void rtboxMsgInit()
        {   //起点接着pl_web的宽度，y点和pl_web平
            this.rtboxMsg.Location = new Point(this.pl_web.Size.Width, this.pl_web.Location.Y);
            //宽度就是预设宽度，高度和pl_web等高
            this.rtboxMsg.Size = new Size(this.rtboxMsg.Width, this.pl_web.Height);
        }
        private void rtbox_Html_Init()
        {
            //x轴从0开始，y就是自身位置。
            rtbox_Html.Location = new Point(0, this.rtbox_Html.Location.Y);
            //宽度和pl_web等宽，高度是全高-自身Y轴
            rtbox_Html.Size = new Size(this.pl_web.Size.Width, this.ClientSize.Height - this.rtbox_Html.Location.Y);
        }
        private void lvBookcaseInit()
        {
            //x和rtboxMsg一致，y和rtbox_Html等高
            this.lvBookcase.Location = new Point(this.rtboxMsg.Location.X, this.rtbox_Html.Location.Y);
            //宽度和rtboxMsg等宽，高和rtbox_Html等高
            this.lvBookcase.Size = new Size(this.rtboxMsg.Width, this.rtbox_Html.Height);
            //初始化视图
            this.lvBookcase.View = View.Details;
            this.lvBookcase.GridLines = true;
            this.lvBookcase.FullRowSelect = true;
            //初始化列
            this.lvBookcase.Columns.Add("书架ID", 60, HorizontalAlignment.Left);
            this.lvBookcase.Columns.Add("书架名称", 60, HorizontalAlignment.Left);
        }
        #endregion

        private delegate void list_Delegate(Dictionary<string, string> ts);
        private void lvBookcaseRefresh(object sender,EventArgs e)
        {
            //外线程调用
            if (InvokeRequired)
            {
                Invoke(new EventHandler(lvBookcaseRefresh), sender,e);
                return;
            }
            Dictionary<string, string> ts = (Dictionary<string, string>)sender;
            this.lvBookcase.BeginUpdate();
            this.lvBookcase.Items.Clear();
            foreach(var bookcase in ts)
            {
                ListViewItem item = new ListViewItem();
                item.Text = bookcase.Key.ToString();
                item.SubItems.Add(bookcase.Value.ToString());
                this.lvBookcase.Items.Add(item);
            }
            this.lvBookcase.EndUpdate();
        }
        private async void HtmlLoadEnd(object sender,FrameLoadEndEventArgs e)
        {
            var obj = (ChromiumWebBrowser)sender;
            string html = await obj.GetSourceAsync();
            SetRtbox_Html(html);
        }


        private delegate void Delegate();
        private delegate void str_Delegate(string str);
        /// <summary>
        /// 设置UI上的Html文本内容
        /// </summary>
        /// <param name="str"></param>
        public void SetRtbox_Html(string html)
        {
            //外线程调用
            if (InvokeRequired)
            {
                Invoke(new str_Delegate(SetRtbox_Html), html);
                return;
            }
            rtbox_Html.Text = html;
        }
        /// <summary>
        /// 设置UI上浏览器地址
        /// </summary>
        /// <param name="str"></param>
        public void SetTxt_Url(string str)
        {
            //外线程调用 
            if (InvokeRequired)
            {
                Invoke(new str_Delegate(SetTxt_Url), str);
                return;
            }
            txt_Url.Text = str;
        }
        public void SetRtboxMsg(MessageTypeEnum ertbox,string msg)
        {
            msg = DateTime.Now + " " + msg + "\r\n";
            if (ertbox == MessageTypeEnum.修改)
            {
                WriteRtboxMsg(msg);
            }
            else
            {
                AppendRtboxMsg(msg);
            }
        }
        /// <summary>
        /// 添加一条消息（事件方法）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddMessageEvent(object sender,AddMessageEventArgs e)
        {
            SetRtboxMsg(e.Type, e.Text);
        }
        private void AppendRtboxMsg(string msg)
        {
            //外线程调用
            if (InvokeRequired)
            {
                Invoke(new str_Delegate(AppendRtboxMsg), msg);
                return;
            }
            rtboxMsg.Text += msg;
        }
        private void WriteRtboxMsg(string msg)
        {
            //外线程调用
            if (InvokeRequired)
            {
                Invoke(new str_Delegate(WriteRtboxMsg), msg);
                return;
            }
            rtboxMsg.Text = msg;
        }
        public void CefSharpUserNameChange(object sender, EventArgs e)
        {
            TextEventArgs te = (TextEventArgs)e;
            if (InvokeRequired)
            {
                Invoke(new EventHandler(CefSharpUserNameChange), sender, e);
                return;
            }
            btn_Login.Text = te.Text;
            UserNameChanged?.Invoke(sender, e);
        }
        private void btn_Url_Click(object sender, EventArgs e)
        {

        }
        private void btn_login_Click(object sender, EventArgs e)
        {
            //formCefSharp.LoginName();
        }


        private void btn_bookrack_Click(object sender, EventArgs e)
        {
            //web_Auto.GetBrowser().MainFrame.ExecuteJavaScriptAsync("document.getElementById('numero2').click();");
            //formCefSharp.LoadBooks();
        }

        private void btnAuto_Click(object sender, EventArgs e)
        {
            AutoWeb();
        }
        public void AutoWeb()
        {
            CefSharpQueue.IsBrowserInit();
            CefSharpQueue.IsLogin();
            CefSharpQueue.RefreshBookshelf();
            return;
            
        }
        private void lvBookcase_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
